package com.ideabove.radio.module;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.graphics.PorterDuff.Mode;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Session;
import com.facebook.android.BaseRequestListener;
import com.facebook.android.Facebook;
import com.facebook.android.Utility;
import com.facebook.android.Hackbook.UserRequestListener;
import com.ideabove.data.Folder;
import com.ideabove.data.PlayItem;
import com.ideabove.data.User;
import com.ideabove.network.NetWorkManager;
import com.ideabove.radio.MainActivity;
import com.ideabove.radio.R;
import com.ideabove.radio.service.PlayBackService;
import com.ideabove.radio.service.PlayBackService.MediaPlayerSingleton;
import com.ideabove.util.ConnectThread;
import com.ideabove.util.Connectivity;
import com.ideabove.util.img.ImageLoader;

public class UserProfileEditMd extends ModuleAbs{
	
	Thread httpThread = null;
	Handler mHandler = new Handler();		

	@SuppressLint("HandlerLeak")
	Handler mMainHandler = new Handler() {

		public void handleMessage(Message msg) {        	 

		}

	};

	public void sendMessage(String msg){
		Message mssg = new Message();
		mssg.obj = msg;
		mMainHandler.sendMessage(mssg);
	}
	


	public interface UserProfileCallback {
		public void callback();
	}

	public void init(MainActivity activity){
		super.init(activity);	
	}
	
	public void showUserProfileEdit(){				
		
		LinearLayout studioMain = (LinearLayout)activity.findViewById(R.id.studio_main);		

		LayoutInflater layoutInflater = (LayoutInflater) 
		activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View viewToInsert = (View)layoutInflater.inflate(R.layout.layout_user_profile, null);	
		studioMain.removeAllViews();
		viewToInsert.setVisibility(View.VISIBLE);
		studioMain.addView(viewToInsert); 
		
		// 엑티비티에 뷰를 세팅한다.
		activity.setCurrentMoudle(this);
		View view = (View)activity.findViewById(R.id.flipper_layout);
		view.setVisibility(View.VISIBLE);
		

		SharedPreferences prefs = activity.getSharedPreferences(FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE); 
		String fbId 		= prefs.getString(FacebookMd.PREFERENCE_USER_FB_ID, "");
		String fbFirstNm 	= prefs.getString(FacebookMd.PREFERENCE_USER_FB_FIRST_NM, "");
		String fbLastNm 	= prefs.getString(FacebookMd.PREFERENCE_USER_FB_LAST_NM, "");
		String fbPicUrl 	= prefs.getString(FacebookMd.PREFERENCE_USER_FB_PIC_URL, "");

		if(fbPicUrl.length() < 1){
			Bundle params = new Bundle();
			params.putString(Facebook.TOKEN, Session.getActiveSession().getAccessToken());
			params.putString("fields", "name, picture, email");
			Utility.mAsyncRunner.request("me", params, new UserRequestListener());
		}else{
			ImageView imageView = (ImageView) activity.findViewById(R.id.user_pf_pic);
			ImageLoader.download(fbPicUrl, imageView);
		}
		
		TextView user_pf_username = (TextView) activity.findViewById(R.id.user_pf_username);
		user_pf_username.setText(fbFirstNm + " " +fbLastNm);

		
		
		// 서버에서 정보 요청
		requestUserProfile();
	}
	

	// 유저 정보를 가져온다.
	public void requestUserProfile(){

		ModuleAbs.showProgressDialog(activity, "", "잠시만 기다려주세요...");

		int timeout = 3;
		new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {
			
			@Override
			public void fail(Object result) {
				// TODO Auto-generated method stub
				ModuleAbs.hideProgressDialog();
				AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
				ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");					
				ab.setPositiveButton("ok", null);  
				ab.show();
			}
			
			@Override
			public void sucess(Object result){
				ModuleAbs.hideProgressDialog();
				displayUserProfileEdit((User)result);
			}
			
			@Override
			public void threadProcess(ConnectThread resultset) throws Exception {
				// TODO Auto-generated method stub					
				HttpClient client = NetWorkManager.getHttpConnection();    
				HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);					

				HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/userSetting.php");
//				Request 
//				a.	user_type : 1 
//				b.	uId : 사용자ID
				
//				-Response
//				a.	user_id : 유저ID
//				b.	fb_id : 페이스북ID
//				c.	club_name : 스튜디오명
//				d.	main_genre : 대표 장르 ID
//				e.	genreIds : 장르ID ( ex : 1,2,3,4,5 )
//				f.	genreNms : 장르명 ( ex : 댄스, 락, 힙합, 메탈 )

				String userId = activity.facebookMd.getBonoUserId();
				
				if(TextUtils.isEmpty(userId)){
					throw new Exception("parameter error");
				}
				
				
				List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				params.add(new BasicNameValuePair("user_type", "1"));
				params.add(new BasicNameValuePair("uId", userId));
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);  

				InputStream in = responsePOST.getEntity().getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				StringBuilder str = new StringBuilder();
				String line = null;
				while((line = reader.readLine()) != null)
				{					
					str.append(line);
				}
				in.close();					
				String jsonStr = str.toString();
				
//				 "user_id":"11",
//				 "fb_id":"1179024862",
//				 "club_name":"32213123213",
//				 "main_genre":"6",
//				 "main_genre_name":"jazz blues",
//				 "genreIds":"1, 2, 3, 4, 6, 7, 11",
//				 "genreNms":"dance, electronic, house, pop, jazz blues, hiphop rap, new age"
				
				
				if(!TextUtils.isEmpty(jsonStr)){
					JSONObject jsonObj = new JSONObject(jsonStr); 
					JSONArray resultArray = jsonObj.getJSONArray("result");

					User user = new User();
					JSONObject jObj = resultArray.getJSONObject(0);
					user.setUser_id(jObj.getString("user_id").toString());
					user.setFb_id(jObj.getString("fb_id").toString());
					user.setClub_name(jObj.getString("club_name").toString());
					user.setMain_genre(jObj.getString("main_genre").toString());
					user.setMain_genre_name(jObj.getString("main_genre_name").toString());
					user.setGenreIds(jObj.getString("genreIds").toString());
					user.setGenreNms(jObj.getString("genreNms").toString());
					
					resultset.setResult(user);
				}
				
			}
		}).start(); 
	}
	
	public void displayUserProfileEdit(User user){
		
		// 클럽명
		TextView user_pf_clubname = (TextView) activity.findViewById(R.id.user_pf_clubname);
		user_pf_clubname.setText(user.getClub_name());
						
		
		// 오늘쪽 상단 버튼
		TextView btn_top_right = (TextView) activity.findViewById(R.id.btn_top_right_text);
		btn_top_right.setText("Save");
		ImageView btn_top_right_img = (ImageView) activity.findViewById(R.id.btn_top_right_img);
		btn_top_right_img.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				ImageView imgView = (ImageView)v;
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					imgView.setPadding(2, 2, 2, 2);
					imgView.setColorFilter(0xaa111111,Mode.SRC_OVER);
				}else if(event.getAction() == MotionEvent.ACTION_UP){	
					
					saveUserProfile();
					
					imgView.setPadding(0, 0, 0, 0);
					imgView.setColorFilter(0x00000000, Mode.SRC_OVER);
				}else if(event.getAction() == MotionEvent.ACTION_CANCEL){
					
					imgView.setPadding(0, 0, 0, 0);
					imgView.setColorFilter(0x00000000, Mode.SRC_OVER);
				}
				
				return true;
			}
		});
		
		// 왼쪽 상단 버튼
		TextView btn_top_left_text = (TextView) activity.findViewById(R.id.btn_top_left_text);
		btn_top_left_text.setText("Cancel");
		ImageView btn_top_left_img = (ImageView) activity.findViewById(R.id.btn_top_left_img);
		btn_top_left_img.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				ImageView imgView = (ImageView)v;
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					imgView.setPadding(2, 2, 2, 2);
					imgView.setColorFilter(0xaa111111,Mode.SRC_OVER);
				}else if(event.getAction() == MotionEvent.ACTION_UP){	
					
					backMd();
					imgView.setPadding(0, 0, 0, 0);
					imgView.setColorFilter(0x00000000, Mode.SRC_OVER);
				}else if(event.getAction() == MotionEvent.ACTION_CANCEL){
					
					imgView.setPadding(0, 0, 0, 0);
					imgView.setColorFilter(0x00000000, Mode.SRC_OVER);
				}
				
				return true;
			}
		});
		
		// 관심 장르를 채크한다.
		String interGenreIds = user.getGenreIds();				
		StringTokenizer st = new StringTokenizer(interGenreIds, ",");		
		LinearLayout inGenresLayout = (LinearLayout)activity.findViewById(R.id.user_interest_genres);
		
		for(int k = 0; k < inGenresLayout.getChildCount(); k++){
			LinearLayout root = (LinearLayout)inGenresLayout.getChildAt(k);
			
			for(int i = 0; i < root.getChildCount(); i++){
				FrameLayout fLayout = (FrameLayout)root.getChildAt(i);
				ImageView tcheck = (ImageView)((FrameLayout)fLayout).getChildAt(1);
				
				while (st.hasMoreElements())
				{
					String token = st.nextToken().trim();
					
					if(token.equals(fLayout.getContentDescription())){
						tcheck.setVisibility(View.VISIBLE);
						// 선택된 대표장르를 보여준다.
						addRepresentativeGenre(fLayout, user.getMain_genre());
					}					
				}	
				
				// 다시 세팅 이유는 커서가 마지막에 와있다 어떻게 첨으로 돌리지;;
				st = new StringTokenizer(interGenreIds, ",");
				
				// 관심장르 버튼에 터치 이벤트를 넣는다.
				setOnTouchEventFromLayout(fLayout);

			}							
		}
		
	}
	
	public void setOnTouchEventFromLayout(FrameLayout fLayout){
		ImageView genreButton = (ImageView)fLayout.getChildAt(0);
		genreButton.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				ImageView view = (ImageView)v;
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					view.setPadding(2, 2, 2, 2);
					view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
				}else if(event.getAction() == MotionEvent.ACTION_UP){
					
					FrameLayout flayout = (FrameLayout)v.getParent();
					
					if(flayout.getChildAt(1).getVisibility() == View.INVISIBLE){
						flayout.getChildAt(1).setVisibility(View.VISIBLE);						
						addRepresentativeGenre(flayout, null);
						
					}else{
						flayout.getChildAt(1).setVisibility(View.INVISIBLE);
						removeRepresentativeGenre(flayout);
					}
					
					switch(v.getId()){
						case R.id.user_pf_img_genre_dence:
												
							break;				
					}
					
					view.setPadding(0, 0, 0, 0);
					view.setColorFilter(0x00000000, Mode.SRC_OVER);			
				}else if(event.getAction() == MotionEvent.ACTION_CANCEL){
					view.setPadding(0, 0, 0, 0);
					view.setColorFilter(0x00000000, Mode.SRC_OVER);
				}
				return true;
			}
		});
	}
	
	

	

	String clubName = null;
	ArrayList<String> interGenres = null;
	ArrayList<String> rpGenres = null;
	
	public static String arrayJoin(String glue, ArrayList<String> array) {
		String result = "";

		for (int i = 0; i < array.size(); i++) {
			result += array.get(i);
			if (i < array.size() - 1) result += glue;
		}
		return result;
	}

	
	public void saveUserProfile(){
		
		// 관심장르 채크
		LinearLayout inGenresLayout = (LinearLayout) activity.findViewById(R.id.user_interest_genres);			
		interGenres = new ArrayList<String>();
		
		for(int k = 0; k < inGenresLayout.getChildCount(); k++){
			LinearLayout root = (LinearLayout)inGenresLayout.getChildAt(k);
			for(int i = 0; i < root.getChildCount(); i++){
				FrameLayout fLayout = (FrameLayout)root.getChildAt(i);
				ImageView tcheck = (ImageView)((FrameLayout)fLayout).getChildAt(1);
				
				if(tcheck != null && tcheck.getVisibility() == View.VISIBLE){					
					interGenres.add((String)fLayout.getContentDescription());
				}				
			}								
		}
		
		// 대표장르 채크
		LinearLayout rpGenresLayout = (LinearLayout) activity.findViewById(R.id.user_rp_genres);			
		rpGenres = new ArrayList<String>();
		
		for(int k = 0; k < rpGenresLayout.getChildCount(); k++){
			LinearLayout root = (LinearLayout)rpGenresLayout.getChildAt(k);
			for(int i = 0; i < root.getChildCount(); i++){
				FrameLayout fLayout = (FrameLayout)root.getChildAt(i);
				ImageView tcheck = (ImageView)((FrameLayout)fLayout).getChildAt(1);
				
				if(tcheck != null && tcheck.getVisibility() == View.VISIBLE){
					rpGenres.add((String)fLayout.getContentDescription());
					k = rpGenresLayout.getChildCount();
					break;
				}				
			}								
		}
		
		// 클럽명 채크		
		EditText cnView = (EditText) activity.findViewById(R.id.user_pf_clubname);
		clubName = cnView.getText().toString();
		
		if(clubName != null && clubName.length() < 1){
			AlertDialog.Builder ab=new AlertDialog.Builder(activity);  
			ab.setMessage("클럽명을 넣어주세요.");  
			ab.setPositiveButton("ok", null);  
			ab.show();
		}else if(interGenres.size() < 1){
			AlertDialog.Builder ab=new AlertDialog.Builder(activity);  
			ab.setMessage("관심장르를 선택해 주세요.");  
			ab.setPositiveButton("ok", null);  
			ab.show();
		}else if(rpGenres.size() < 1){
			AlertDialog.Builder ab=new AlertDialog.Builder(activity);  
			ab.setMessage("대표장르를 선택해 주세요.");  
			ab.setPositiveButton("ok", null);  
			ab.show();
		}else{
			// 완벽하다면..
			ModuleAbs.showProgressDialog(activity, "", "잠시만 기다려주세요...");
			
			int timeout = 3;
			new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {
				
				@Override
				public void fail(Object result) {
					// TODO Auto-generated method stub
					ModuleAbs.hideProgressDialog();
					AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
					ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");					
					ab.setPositiveButton("ok", null);  
					ab.show();
				}
				
				@Override
				public void sucess(Object result){
					ModuleAbs.hideProgressDialog();
					AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
					ab.setMessage("저장되었습니다.");					
					ab.setPositiveButton("ok", new OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							mAddTotalCnt = 0;
							activity.folderEditMd.showFolderEditList(null);
						}
					});  
					ab.show();
					
					// 소스가 난리가 나서
//					if(upcallback != null){
//						upcallback.callback();
//						upcallback = null;
//					}
				}
				
				@Override
				public void threadProcess(ConnectThread resultset) throws Exception {
					// TODO Auto-generated method stub					
					HttpClient client = NetWorkManager.getHttpConnection();    
					HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);					

					HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/userSetting.php");
//					a.	user_type : 2
//					b.	uId : 유저 ID
//					c.	club_title : 스튜디오명
//					d.	main_genre : 메인장르
//					e.	genre_ids : 장르ID들 ( ex : 1,3,5,7,9 )

					String buserId = activity.facebookMd.getBonoUserId();
					
					if(buserId == null || clubName == null || buserId.length() < 1|| interGenres.size() < 1 || rpGenres.size() < 1){
						throw new Exception("parameter error");
					}
					
					
					List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
					params.add(new BasicNameValuePair("user_type", "2"));
					params.add(new BasicNameValuePair("uId", buserId));
					params.add(new BasicNameValuePair("club_title", clubName));
					params.add(new BasicNameValuePair("main_genre", rpGenres.get(0)));
					params.add(new BasicNameValuePair("genre_ids", arrayJoin(",",interGenres) ));
					
					UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
					post.setEntity(ent);
					HttpResponse responsePOST = client.execute(post);  

					InputStream in = responsePOST.getEntity().getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(in));
					StringBuilder str = new StringBuilder();
					String line = null;
					while((line = reader.readLine()) != null)
					{					
						str.append(line);
					}
					in.close();					
					String jsonStr = str.toString();
					
					if(!"1".equals(jsonStr)){
						throw new Exception("fail");
					}
					
				}
			}).start(); 
		}		
	}
	

	public class UserRequestListener extends BaseRequestListener {

		@Override
		public void onComplete(final String response, final Object state) {
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(response);

				final String picURL = jsonObject.getJSONObject("picture")
						.getJSONObject("data").getString("url");
				final String name = jsonObject.getString("name");
				Utility.userUID = jsonObject.getString("id");
				
				
				SharedPreferences prefs = activity.getSharedPreferences(FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE ); 
				SharedPreferences.Editor editor = prefs.edit();					
				editor.putString(FacebookMd.PREFERENCE_USER_FB_PIC_URL, picURL);
				editor.commit();

				mHandler.post(new Runnable() {
					@Override
					public void run() {
						ImageView imageView = (ImageView) activity.findViewById(R.id.user_pf_pic);
						ImageLoader.download(picURL, imageView);
					}
				});

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}
	
	private int mAddTotalCnt = 0;
	LinearLayout mLineLayout = null;
	
	public void addRepresentativeGenre(FrameLayout view, String repGenreId){
		LinearLayout rpGenresLayout = (LinearLayout) activity.findViewById(R.id.user_rp_genres);

		
		// 네줄식 나눠 담기
		
		if(mAddTotalCnt % 4 == 0){
			mLineLayout = new LinearLayout(activity);
			mLineLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
					LinearLayout.LayoutParams.WRAP_CONTENT));
			mLineLayout.setOrientation(LinearLayout.HORIZONTAL);
		}else{
			mLineLayout = (LinearLayout) rpGenresLayout.getChildAt(rpGenresLayout.getChildCount() - 1);
		}
		
		FrameLayout fLayout = new FrameLayout(activity);
		fLayout.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
		                    LayoutParams.WRAP_CONTENT));			
		fLayout.setTag(view.getTag());		
		fLayout.setContentDescription(view.getContentDescription());
		
		
		fLayout.setClickable(true);
		fLayout.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
			
				// and than check
				ImageView genre = (ImageView)((FrameLayout)v).getChildAt(0);
				ImageView check = (ImageView)((FrameLayout)v).getChildAt(1);
				
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					genre.setPadding(2, 2, 2, 2);
					genre.setColorFilter(0xaa111111,Mode.SRC_OVER);				
				}else if(event.getAction() == MotionEvent.ACTION_UP){
					

					// all check remove
					LinearLayout rpGenresLayout = (LinearLayout) activity.findViewById(R.id.user_rp_genres);				
					for(int k = 0; k < rpGenresLayout.getChildCount(); k++){
						LinearLayout root = (LinearLayout)rpGenresLayout.getChildAt(k);
						for(int i = 0; i < root.getChildCount(); i++){
							FrameLayout fLayout = (FrameLayout)root.getChildAt(i);
							for(int j = 0; j < fLayout.getChildCount(); j++){
								ImageView tcheck = (ImageView)((FrameLayout)fLayout).getChildAt(1);
								tcheck.setVisibility(View.INVISIBLE);						
							}
						}								
					}
					
					if(check.getVisibility() == View.INVISIBLE){
						check.setVisibility(View.VISIBLE);
					}else{
						check.setVisibility(View.INVISIBLE);
					}
				}
				genre.setPadding(0, 0, 0, 0);
				genre.setColorFilter(0x00000000, Mode.SRC_OVER);				
				return true;
			}
		});
		
			// imageview add
			ImageView imageGenre = new ImageView(view.getContext());
			View genreView = view.getChildAt(0);				
			imageGenre.setLayoutParams(genreView.getLayoutParams());			
			imageGenre.setImageResource(view.getResources().getIdentifier((String)genreView.getTag(), "drawable", activity.getPackageName()));

			// imageview add
			ImageView imageCheck = new ImageView(view.getContext());			
			View checkView = view.getChildAt(1);						
			imageCheck.setLayoutParams(checkView.getLayoutParams());			
			imageCheck.setImageResource(checkView.getResources().getIdentifier((String)checkView.getTag(), "drawable", activity.getPackageName()));
			imageCheck.setVisibility(View.INVISIBLE);
		
		fLayout.addView(imageGenre);
		fLayout.addView(imageCheck);
		

		// 대표장를 채크한다.
		if(repGenreId != null && repGenreId.equals(fLayout.getContentDescription())){			
			fLayout.getChildAt(1).setVisibility(View.VISIBLE);
		}
		
		if(mAddTotalCnt % 4 == 0){
			mLineLayout.addView(fLayout);		
			rpGenresLayout.addView(mLineLayout);
		}else{
			mLineLayout.addView(fLayout);
		}
		
		
		
		mAddTotalCnt++;
	}
	
	
	public void removeRepresentativeGenre(FrameLayout view){
		LinearLayout reGenresLayout = (LinearLayout) activity.findViewById(R.id.user_rp_genres);
		FrameLayout viewForRemove = null;
		LinearLayout linearLayout = null;
		for(int i = 0; i < reGenresLayout.getChildCount(); i++){
			linearLayout = (LinearLayout)reGenresLayout.getChildAt(i);			
			
			for(int j = 0; j < linearLayout.getChildCount(); j++){
				viewForRemove = (FrameLayout)linearLayout.getChildAt(j);
					
				if(view.getTag() != null && view.getTag().equals(viewForRemove.getTag())){
					i = reGenresLayout.getChildCount();
					break;
				}			
			}
		}		
		
		if(linearLayout != null){
			linearLayout.removeView(viewForRemove);
			if(linearLayout.getChildCount() == 0){				
				reGenresLayout.removeView(linearLayout);
			}
		}
		
		sortView(view);
		mAddTotalCnt--;
	}
	
	public void sortView(FrameLayout view){
		LinearLayout reGenresLayout = (LinearLayout) activity.findViewById(R.id.user_rp_genres);
		LinearLayout beforeLayout = null;
		for(int i = 0; i < reGenresLayout.getChildCount(); i++){
			beforeLayout = (LinearLayout)reGenresLayout.getChildAt(i);
			
			if(beforeLayout.getChildCount() < 4){
				
				// 다음 레이아웃이 있다면
				if(i + 1 != reGenresLayout.getChildCount()){
					LinearLayout nextLayout = (LinearLayout)reGenresLayout.getChildAt(i + 1);
										
					View viewToInsert = nextLayout.getChildAt(0);
					nextLayout.removeView(viewToInsert);
					beforeLayout.addView(viewToInsert);
					
					// 뷰가없다면 지운다.
					if(nextLayout.getChildCount() == 0){
						reGenresLayout.removeView(nextLayout);
					}
				}
				
			}		
		}	
	}
	
	@Override
	public void backMd() {
		// TODO Auto-generated method stub
		mAddTotalCnt = 0;
		activity.folderEditMd.showFolderEditList(null);		
	}
	
}
